#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "imgstitcher.h"
#include <QFileDialog>
#include <QMessageBox>
#include <string>
#include <QTextCodec>
#include <deque>
#include <QDebug>

using namespace std;

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    // 选择图片按钮
    connect(ui->btnSelectImg, &QPushButton::clicked, this, [=](){
        vector<string> imgPaths = this->selectPaths();
        if (imgPaths.size() == 0) return;
        for (string str : imgPaths) {
            ui->labImg->addImg(imread(str, cv::IMREAD_UNCHANGED));
        }
        ui->labImg->showImg(0);
    });
    // 图像拼接按钮
    connect(ui->btnStitchImg, &QPushButton::clicked, this, [=](){
        this->stitchImg(ui->labImg->m_Imgs);
    });
    // 读取模板按钮
    ui->labMatchImg->hideBtn();
    ui->labMatchImg->setCapcity(1);
    connect(ui->btnGetTmp, &QPushButton::clicked, this, [=](){
        vector<string> imgPath = selectPaths();
        if (imgPath.size() == 0) return;
        ui->labMatchImg->addImg(imread(imgPath[0], cv::IMREAD_UNCHANGED));
        ui->labMatchImg->showImg(0);
    });
    // 模板匹配按钮
    connect(ui->btnMatch, &QPushButton::clicked, this, [=](){
        cv::Mat outImg = ImgStitcher::matchImage(m_totalImg, ui->labMatchImg->m_Imgs[0]);
        cv::Mat theImg;
        int res = ImgStitcher::evaluateRes(outImg, ui->labMatchImg->m_Imgs[0], theImg);
        qDebug() << "匹配结果，像素值不同的像素点个数为：" << res;
        imshow("theImg", theImg);
    });
}

MainWindow::~MainWindow()
{
    delete ui;
}


vector<string> MainWindow::selectPaths() {
    vector<string> ret;
    QStringList imgPaths = QFileDialog::getOpenFileNames(this, tr("选择图片"), "E:\\Desktop", "*.png *.jpg *.bmp *.tif");
    QTextCodec* code = QTextCodec::codecForName("GB2312");//解决中文路径问题
    for (QString str : imgPaths) {
        ret.push_back(code->fromUnicode(str).data());
    }
    return ret;
}

// 拼接图像
void MainWindow::stitchImg(deque<cv::Mat> imgs) {
//    cv::Mat image0 = cv::imread("E:\\Desktop\\Qt-ImageStitch\\ImageStitch\\res\\0.bmp", IMREAD_UNCHANGED);
//    cv::Mat image1 = cv::imread("E:\\Desktop\\Qt-ImageStitch\\ImageStitch\\res\\1.bmp", IMREAD_UNCHANGED);
//    cv::Mat image2 = cv::imread("E:\\Desktop\\Qt-ImageStitch\\ImageStitch\\res\\2.bmp", IMREAD_UNCHANGED);
//    cv::imshow("image0", image0);
//    cv::imshow("image1", image1);
//    cv::imshow("image2", image2);
//    vector<cv::Mat> imgs = {image0, image1, image2};
    m_totalImg = ImgStitcher::stitchImgs(imgs);
    imshow("StitchResult", m_totalImg);
    cv::Mat refImg = cv::imread("E:\\Desktop\\Qt-ImageStitch\\ImageStitch\\res\\orignal.bmp", IMREAD_UNCHANGED);
    cv::Mat theImg;
    int res = ImgStitcher::evaluateRes(m_totalImg, refImg, theImg);
    imshow("theImg", theImg);
    qDebug() << "拼接结果,像素值不同的像素个数为：" << res;
}
